#ifndef _time_c__ruffi__eurobot08_
#define _time_c__ruffi__eurobot08_

#include <avr/interrupt.h>
#include <avr/io.h>
#include <math.h>
#include "dim.c"
#include "motors.c"

//pocitadlo casu
volatile long int time;
//promenne pro trideni micku
volatile char curr_c;
volatile unsigned long int time_c = 0;
volatile unsigned long int max_time_c = 0;
volatile int last_c = 0;
//promenne pro pocitani micku
volatile char last_in = 0;
volatile char in;
volatile char last_out = 0;
volatile char out;
volatile char l_left, last_l_left = 1;
volatile char l_center, last_l_center = 1;
volatile char l_right, last_l_right = 1;

void init_timer ( void ) {
/* Timer1, 16bit
*  casovy limit 90s
*  externi oscilator: 32768 kHz
*/
	/*no prescale */
	TCCR1B |= (1<<CS10);
	/*pocatecni hodnota pocitadla*/
	TCNT1 = 0;
	/*povoleni preruseni pri preteceni timeru1*/
	TIMSK |= (1<<TOIE1);
}

void start_time( void ) {
	time = 0;
}

ISR(TIMER1_OVF_vect) {
	/* frekvence= 128Hz */
	time++;

	/*vevnitr 3 a vic micku - pro jistotu - zastavit sbirani */
	if ( balls_inside >=3) conveyor_down();

	/*konec*/
	if (time >= 11520) { //90s
		//prasarna, ale tady to nevadi
		// zastavit motory
		right(0);
		left(0);
		gate_up();//vysypat micky, co jsou vevnitr.
		conveyor_down();
		delay(500);
		gate_stop();
		delay(500);
		conveyor_stop();
		cli(); //zakazat preruseni
		led(0); //zasnout ledku
		while(1){ delay(50); } //konec
	}

	/**********************************
	** rozdelovani micku podle barvy **
	**********************************/
	curr_c = get_color_sensor();
	if ( ( curr_c == 0 ) && (curr_c == last_c ) ){
		time_c++;
	} else {
		time_c=0;
		flap_up();
	}
	if ( time_c > max_time_c ) max_time_c = time_c;
	last_c = curr_c;
	/* po 100/128 s bez signalu muzu sklopit */
	if ( max_time_c > 100 ) {
		flap_down();
		max_time_c = 0;
	}

	/*********************
	** pocitani dobrych **
	** a spatnych micku **
	*********************/
	//spadl dovnitr
	in = get_ball_inside();
	if (( in != last_in ) && (in == 0)) good_balls++;
	last_in = in;
	//vypadl ven
	out = get_ball_outside();
	if (( out != last_out ) && (out == 0)) balls_inside--;
	last_out = out;
	//prijel levym vytahem
	l_left = get_left_lift();
	if (( l_left != last_l_left ) && (l_left == 0)) balls_inside++;
	last_l_left = l_left;
	//prijel prostrednim vytahem
	l_center = get_center_lift();
	if (( l_center != last_l_center ) && (l_center == 0)) balls_inside++;
	last_l_center = l_center;
	//prijel pravym vytahem
	l_right = get_right_lift();
	if (( l_right != last_l_right ) && (l_right == 0)) balls_inside++;
	last_l_right = l_right;
}

#endif
